package com.zlj.accountant.core;

import java.util.List;

import android.content.Context;

import com.zlj.accountant.core.AbstractService.OneKeyResultListProvider;
import com.zlj.accountant.core.AbstractService.OneKeyResultProvider;
import com.zlj.accountant.core.AbstractService.ResultListProvider;
import com.zlj.accountant.core.AbstractService.ResultProvider;
import com.zlj.accountant.core.AbstractService.SimplerHandler;
import com.zlj.accountant.core.AbstractService.TaskHandler;

public class DBHandler implements HandlerManager{
	
	private final static String tag = DBHandler.class.getName();
	
	private Context context;
	
	public DBHandler(Context context){
		this.context = context;
    }
	
	

	@SuppressWarnings({"unchecked", "rawtypes"})
	@Override
	public <T,P> List<T> getList(Class<T> t, P key)throws Exception {
		ServiceManager manager = ServiceManager.getInstance(context);
		final OneKeyResultListProvider provider = manager.getResultListProvider(t, key.getClass());
	    return provider.provide(this,key);
	}

	@SuppressWarnings({"unchecked", "rawtypes"})
    public <T,P> T find(Class<T> t, P key)throws Exception{
		ServiceManager manager = ServiceManager.getInstance(context);
		final OneKeyResultProvider provider = manager.getResultProvider(t, key.getClass());
		return (T)provider.provide(this,key);
	}

    public <T> List<T> getList(Class<T> t)throws Exception{
		ServiceManager manager = ServiceManager.getInstance(context);
		ResultListProvider<T> provider = (ResultListProvider<T>)manager.getResultListProvider(t, Void.class);
		return provider.provide(this);
    }

    public <T> T find(Class<T> t)throws Exception{
    	ServiceManager manager = ServiceManager.getInstance(context);
    	ResultProvider<T> provider = (ResultProvider<T>)manager.getResultProvider(t, Void.class);
    	return provider.provide(this);
    }

    public <TTask extends Task<TMethod>,TMethod extends Enum<TMethod>> void handle(TTask task,
            TMethod e)throws Exception
    {
	    ServiceManager manager = ServiceManager.getInstance(context);
	    @SuppressWarnings("unchecked")
        TaskHandler<TTask,TMethod> handler = manager.getTaskMandler(task.getClass(), e);
	    handler.handle(this,task);
    }

	@SuppressWarnings("unchecked")
    public <TTask extends SimpleTask> void handle(TTask task)throws Exception{
	    ServiceManager manager = ServiceManager.getInstance(context);
	    SimplerHandler<TTask> handler = (SimplerHandler<TTask>)manager.getSimpleHandler(task.getClass());
	    handler.handle(this,task);
    }

	@Override
	public Context getContext(){
	    return context;
	}
	
}
